<template>
    <div v-loading="loading" class="console-page">
        <el-form inline :model="searchForm" class="e-page form-item" spellcheck="false" @submit.native.prevent>
            <el-row class="toolbar" ref="el">
                <el-col :span="3" style="padding-right: 5px">
                    <el-input v-model="searchForm.name" placeholder="接口名称,%模糊匹配" clearable class="input-auto-resize" />
                </el-col>
                <el-col :span="3" style="padding-right: 5px">
                    <el-input v-model="searchForm.url" placeholder="接口地址,%模糊匹配" clearable class="input-auto-resize" />
                </el-col>
                <el-col :span="3" style="padding-right: 5px">
                    <el-select v-model="searchForm.status" style="width: 100%" class="input-auto-resize" clearable
                        placeholder="请选择接口状态">
                        <el-option label="已发布" value="1" />
                        <el-option label="草稿" value="0" />
                    </el-select>
                </el-col>
                <el-col :span="3" style="padding-right: 5px">
                    <el-select v-model="searchForm.method" style="width: 100%" sclass="input-auto-resize" clearable
                        placeholder="请选择接口方法">
                        <el-option label="GET" value="get" />
                        <el-option label="POST" value="post" />
                    </el-select>
                </el-col>
                <el-col :span="3" style="padding-right: 5px" v-permission="$permission.Update">
                    <el-select v-model="searchForm.type" style="width: 100%" class="input-auto-resize" clearable
                        placeholder="请选择接口类型">
                        <el-option label="SQL" value="sql" />
                        <el-option label="JAVA" value="java" />
                        <el-option label="HTML" value="html" />
                    </el-select>
                </el-col>
                <el-col :span="3" style="padding-right: 5px">
                    <el-select v-model="searchForm.apiType" style="width: 100%" class="input-auto-resize" clearable
                        placeholder="请选择接口开放类型">
                        <el-option label="内部接口" value="1" />
                        <el-option label="开放接口" value="0" />
                    </el-select>
                </el-col>
                <el-col :span="3" style="padding-right: 5px">
                    <el-select v-model="searchForm.group" style="width: 100%" class="input-auto-resize" clearable
                        placeholder="请选择接口标签">
                        <el-option :label="item" :value="item" v-for="(item, index) in inGroupListShow" :key="index" />
                        <template #footer>
                            <el-input v-model="groupInput" class="input-auto-resize" placeholder="标签名称" />
                        </template>
                    </el-select>
                </el-col>
                <el-col :span="1" style="padding-right: 5px">
                    <el-button type="primary" @click="searchTable" circle class="button-auto-resize"
                        :loading="bt_loading" native-type="submit" :icon="getIcon('search')">
                    </el-button>
                </el-col>
                <el-col :span="2" style="justify-content: right;display:flex;">
                    <el-button :icon="getIcon('link')" class="button-auto-resize" circle @click="cache"
                        v-permission="$permission.Update" />
                    <el-button :icon="getIcon('plus')" class="button-auto-resize" circle @click="edit('new')"
                        v-permission="$permission.Write" />
                </el-col>
            </el-row>
        </el-form>
        <el-table :data="tableData" border header-cell-class-name="el-table-header-cell" cell-class-name="el-table-cell"
            class="e-page table-with-pagination" ref="tableRef" highlight-current-row>
            <el-table-column prop="interfaceName" label="接口名称" :width="fontAutoResize.size_15.value" />
            <el-table-column prop="url" label="url地址" width="250">
                <template #default="scope">
                    {{ scope.row.url }}
                </template>
            </el-table-column>
            <el-table-column prop="method" label="方法" :width="fontAutoResize.size_6.value">
                <template #default="scope">
                    <el-tag :disable-transitions="true" class="button-auto-resize"
                        :type="(scope.row.method ? scope.row.method.toUpperCase() : '') === 'GET' ? 'warning' : 'primary'">
                        {{ scope.row.method ? scope.row.method.toUpperCase() : '' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="method" label="开放类型" :width="fontAutoResize.size_7.value">
                <template #default="scope">
                    <el-tag :type="scope.row.apiType ? 'warning' : 'primary'" class="button-auto-resize"
                        :disable-transitions="true">
                        {{ scope.row.apiType ? '内部接口' : '开放接口' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="type" label="接口类型" :width="fontAutoResize.size_6.value"
                v-permission="$permission.Update">
                <template #default="scope">
                    <el-tag type="primary" class="button-auto-resize" :disable-transitions="true">
                        {{ scope.row.type ? scope.row.type.toUpperCase() : "未知类型" }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="comments" label="备注说明" :min-width="fontAutoResize.size_18.value" />
            <el-table-column prop="inGroup" label="分组标签" :min-width="fontAutoResize.size_10.value" />
            <el-table-column prop="status" label="状态" :width="fontAutoResize.size_6.value">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'info'" class="button-auto-resize"
                        :disable-transitions="true">
                        {{ scope.row.status === 1 ? "已发布" : "草稿" }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="checkPermission" label="权限验证" :width="fontAutoResize.size_6.value">
                <template #default="scope">
                    <el-tag :type="scope.row.checkPermission === 1 ? 'success' : 'info'" class="button-auto-resize"
                        :disable-transitions="true">
                        {{ scope.row.checkPermission === 1 ? "开启" : "关闭" }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="useCache" label="数据缓存" :width="fontAutoResize.size_6.value">
                <template #default="scope">
                    <el-tag :type="scope.row.useCache > 0 ? 'success' : 'info'" class="button-auto-resize"
                        :disable-transitions="true">
                        {{ scope.row.useCache > 0 ? "开启" : "关闭" }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="encrypt" label="数据加密" :width="fontAutoResize.size_6.value">
                <template #default="scope">
                    <el-tag :type="scope.row.encrypt === 0 ? 'info' : 'success'" class="button-auto-resize"
                        :disable-transitions="true">
                        {{ scope.row.encrypt === 0 ? "关闭" : "开启" }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="crtTime" label="创建时间" :width="fontAutoResize.size_11.value" />
            <el-table-column prop="updateTime" label="更新时间" :width="fontAutoResize.size_11.value" />
            <el-table-column fixed="right" label="操作" :width="operationWidth" className="operation-column">
                <template #default="scope">
                    <el-button type="primary" :icon="getIcon('editPen')" class="button-auto-resize" circle
                        @click="edit(scope.row)" v-permission="$permission.Update" />
                    <el-button type="primary" :icon="getIcon('document')" class="button-auto-resize" circle
                        @click="intoApiDoc(scope.row)" :disabled="!scope.row.status"/>
                    <el-button type="danger" :icon="getIcon('delete')" class="button-auto-resize" circle
                        @click="del(scope.row)" confirm-title="是否确认删除该接口?" v-permission="$permission.Delete" />
                </template>
            </el-table-column>
        </el-table>
        <div style="height: 50px;">
            <el-pagination background @size-change="SizeChange" @current-change="CurrentChange"
                :current-page="currentPage" :page-sizes="page_sizes" :page-size="page_size"
                layout="total, sizes, prev, pager, next, jumper" prev-text="<上一页" next-text="下一页>" :total="total"
                class="e-page">
            </el-pagination>
        </div>
        <el-dialog v-model="showPreviewPage" fullscreen class="preview-page forbid-select" append-to-body
            destroy-on-close>
            <div class="close-button iconfont icon-close" @click="showPreviewPage = false" />
            <iframe :id="previewPageUrl" :src="previewPageUrl" frameborder="0" width="100%" height="100%" />
        </el-dialog>
    </div>
</template>

<script setup>
import { checkUrl, getIcon } from "@/utils/tools"
import { useElMessage, useSetTableOperationWidth, useRequest } from "@usehook"
import router from "@/router"
import { fontAutoResize } from "@/utils/setting"
import storeInstance from "@/pinia"
import { apiPrefix } from "@/utils/constant"

const { tagMenuStore } = storeInstance
const operationWidth = useSetTableOperationWidth(3)
let tableData = $ref([])
let currentPage = $ref(1)
let page_size = $ref(0)
let total = $ref(0)
let searchForm = $ref({
    name: '',
    url: '',
    status: '1',
    method: '',
    type: '',
    apiType: '',
    group: ""
})
let groupInput = $ref("")
let inGroupList = $ref([])
let loading = $ref(false)
let bt_loading = $ref(false)
let page_sizes = [10, 30, 50, 100, 200]
let showPreviewPage = $ref(false)
let previewPageUrl = $ref("")

const inGroupListShow = computed(() => {
    return groupInput ? inGroupList.filter((item) => item.includes(groupInput)) : inGroupList
})

const cache = () => {
    useRequest({ url: "/interface/cache", method: "post", loadingMessage: "正在重新生成接口缓存数据" }).then(resp => {
        if (resp && resp.status) {
            useElMessage("成功生成" + resp.data + "个已发布接口的缓存数据")
        }
    })
}
const del = (row) => {
    //查找tagMenu中是否存在打开的页签，有就一起删除
    for (let tagMenu of tagMenuStore.getTagMenu) {
        if (tagMenu.path === '/interface/detail?sequence=' + row.sequence) {
            tagMenuStore.closeTagMenu(tagMenu)
        }
    }
    useRequest({ url: "/interface/delete", sequence: row.sequence, method: "post" }).then(resp => {
        if (resp && resp.status) {
            useElMessage("数据库删除" + resp.data.db + "条记录, 缓存删除" + resp.data.cache + "条记录")
            getData()
        }
    })
}

const intoApiDoc = (row) => {
    if (row.type === "html") {
        showPreviewPage = true
        previewPageUrl = apiPrefix + row.url
    } else {
        const sequence = row.sequence
        const index = '/interface/api?sequence=' + sequence
        tagMenuStore.setTitle(row.comments || row.interfaceName)
        if (checkUrl(index)) router.push(index);
    }
}

const edit = (row) => {
    let index;
    if (row === 'new') {
        index = '/interface/detail'
        tagMenuStore.setTitle(row)
    } else {
        const sequence = row.sequence
        index = '/interface/detail?sequence=' + sequence
        tagMenuStore.setTitle(row.comments || row.interfaceName)
    }
    if (checkUrl(index)) router.push(index);
}
const getInterfaceInfo = (params) => {
    loading = true;
    bt_loading = true;
    useRequest(params).then(resp => {
        if (resp) {
            if (resp.status) { //0表示成功，1表示失败
                tableData = resp.data;
                total = resp.totalRecord;
            } else if (resp.message) useElMessage(resp.message);
        }
    }).finally(_ => {
        loading = false;
        bt_loading = false;
    })
}
const searchTable = () => {
    getInterfaceInfo({
        'url': '/interface/data', 'search': JSON.stringify(searchForm), 'limit': page_size, 'page': 1
    });
    currentPage = 1;
}
const SizeChange = (val) => {
    getInterfaceInfo({
        'url': '/interface/data', 'search': JSON.stringify(searchForm), 'limit': val, 'page': currentPage
    });
    page_size = val;
}
const CurrentChange = (val) => {
    getInterfaceInfo({
        'url': '/interface/data', 'search': JSON.stringify(searchForm), 'limit': page_size, 'page': val
    });
    currentPage = val;
}
const getData = () => {
    getInterfaceInfo({
        'url': '/interface/data', 'search': JSON.stringify(searchForm), 'limit': page_size, 'page': currentPage
    });
}

onMounted(() => {
    page_size = page_sizes[1]
    getData()
    useRequest("/interface/group").then((resp) => {
        if (resp && resp.status) {
            inGroupList = resp.data
        }
    })
})
</script>

<style scoped>
:deep(.upload) {
    margin: 0 3px;
}

:deep(.el-upload-list) {
    display: none;
}
</style>

<style>
.preview-page .el-dialog__body {
    padding: 0;
    height: 100%;
    width: 100%;
    overflow: hidden;
    position: relative;
}

.preview-page .close-button {
    position: absolute;
    right: 5px;
    top: 5px;
    font-size: 18px;
    background: rgb(255 255 255 / 60%);
    border-radius: 50%;
    padding: 5px;
}

.preview-page .el-dialog__header {
    display: none
}
</style>